/**
 * Created by eaTong on 2018/12/5 .
 * Description:
 */
import React from 'react';
import {Container, Header, Content, Form, CheckBox, Body, List, ListItem, Text, View, Button, Toast} from 'native-base';
import ajax from "../utils/ajax";

let saveGrant;
export default class EmployeeManage extends React.Component {
  static navigationOptions = ({navigation}) => {
    return {
      title: '视野分配',
      headerRight: (
        <Button transparent onPress={() => saveGrant()}>
          <Text style={{color: '#3142FF', fontSize: 16}}>保存</Text>
        </Button>
      ),
    }
  };
  state = {
    grantedUsers: [],
    selectedDepartment: '',
    employees: []
  };

  componentDidMount() {
    this.employee = this.props.navigation.state.params.employee;
    this.getEmployees();
    this.getGrantedUsers();

    saveGrant = this.saveGrant.bind(this);
  }

  async getEmployees() {
    const employees = await ajax({url: '/api/employee/list'});
    this.setState({
      employees
    });
  }

  async getGrantedUsers() {
    const grantedUsers = await ajax({
      url: '/api/authority/view/get_users_view',
      data: {user_id: this.employee.user_id}
    });
    this.setState({
      grantedUsers
    });
  }

  onCheckEmployee(checked, id) {
    let {grantedUsers} = this.state;

    if(checked){
      grantedUsers.push(id);
    }else{
      grantedUsers = grantedUsers.filter(item =>item !== id);
    }

    this.setState({grantedUsers})

  }

  async saveGrant() {

    console.log({user_id: this.employee.user_id, view_users_id: this.state.grantedUsers});
    const grantedUsers = await ajax({
      url: '/api/authority/view/set_users_view',
      data: {user_id: this.employee.user_id, view_users_id: this.state.grantedUsers}
    });
    // Toast.
    Toast.show({
      text: "保存成功",
      duration: 3000,
      position: "top"
    });
  }

  render() {
    const {grantedUsers, employees} = this.state;
    return (
      <Container>
        <Content>
          <List>

            {employees.map(employee => {
              const checked = grantedUsers.indexOf(employee.id) !== -1;
              return (
                <ListItem key={employee.id} style={{display: 'flex'}}
                          onPress={() => this.onCheckEmployee(!checked, employee.id)}>
                  <Body style={{flex: 1}}>
                  <Text>{employee.name}</Text>
                  </Body>
                  <CheckBox checked={checked}>
                  </CheckBox>
                </ListItem>
              )
            })}
          </List>

        </Content>
      </Container>
    );
  }
}
